﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings

using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Caching;
using Utilities.DataTypes;
using Utilities.Events.EventArgs;
using OptimizerPrime.BaseClasses;
using Utilities.Web.ExtensionMethods;

#endregion

namespace OptimizerPrime.HttpHandlers
{
    /// <summary>
    /// Handler that compresses the CSS files in themes,
    /// attached to headers, etc.
    /// </summary>
    public class CSSHandler : BaseHandler
    {
        #region Public Functions

        /// <summary>
        /// Processes the request
        /// </summary>
        /// <param name="context">Current context</param>
        public override void ProcessRequest(HttpContext context)
        {
            if (string.IsNullOrEmpty(context.Request.QueryString["Name"]))
                return;
            if (!OnStart(new OnStartEventArgs()))
                return;
            string FileName = context.Request.QueryString["Name"];
            if (Utils.Generic.SetHeaders(FileName, context, "text/css"))
            {
                ReduceCSS(FileName, context);
                context.HTTPCompress();
            }
            OnEnd(new OnEndEventArgs());
        }

        /// <summary>
        /// This item is not reusable
        /// </summary>
        public override bool IsReusable
        {
            get { return false; }
        }

        #endregion

        #region Private Static Functions

        /// <summary>
        /// Reduces the CSS file, removing whitespace, etc.
        /// </summary>
        /// <param name="File">Files to reduce (comma seperated)</param>
        /// <param name="context">current context</param>
        private static void ReduceCSS(string File, HttpContext context)
        {
            string[] Splitter = { "," };
            string[] Files = File.Split(Splitter, StringSplitOptions.RemoveEmptyEntries);

            foreach (string FileUsing in Files)
            {
                string CurrentFile = context.Server.MapPath(FileUsing);
                if (!CurrentFile.EndsWith(".css", StringComparison.OrdinalIgnoreCase))
                    throw new System.Security.SecurityException("No access");
                if (new FileInfo(CurrentFile).Exists)
                {
                    Tuple<string, DateTime> Result = (Tuple<string, DateTime>)context.Cache[CurrentFile];
                    if (Result == null)
                    {
                        using (StreamReader Reader = new StreamReader(CurrentFile))
                        {
                            Result = new Tuple<string, DateTime>(Reader.ReadToEnd().Minify(MinificationType.CSS), System.IO.File.GetLastWriteTime(CurrentFile));
                            context.Cache.Insert(CurrentFile, Result, new CacheDependency(CurrentFile));
                        }
                    }
                    context.Response.Write(Result.Item1);
                }
            }
        }

        #endregion
    }
}